# !/usr/bin/env python
# coding: utf-8
# @Time    : 2017/11/1 14:49
# @Author  : 6imensiva
# @Site    : https://gitee.com/dimensiva/app_server.git
# @File    : my_time.py
# @Software: PyCharm
# @Version: 3.5.4

import time
from threading import Thread
from threading import Event
import datetime
import calendar


def get_timestamp():
	t = time.time()
	return int(round(t * 1000))


def add_date(date_str, add):
	src_date = datetime.datetime.strptime(date_str, '%Y-%m-%d')
	dst_date = src_date + datetime.timedelta(days=add)
	return dst_date.strftime('%Y-%m-%d')


def get_now():
	return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))


def get_date():
	return time.strftime('%Y-%m-%d', time.localtime(time.time()))


def format_date(date_str):
	if date_str is None or date_str =='':
		return None
	return time.strptime(date_str,'%Y-%m-%d')


def day_iterator_by_month(year, month):
	month_range = calendar.monthrange(year, month)[1]
	for i in range(1, month_range + 1):
		yield i


class _Timer(Thread):
	"""Call a function after a specified number of seconds:

			t = Timer(30.0, f, args=[], kwargs={})
			t.start()
			t.cancel()     # stop the timer's action if it's still waiting

	"""

	def __init__(self, interval, function, args=[], kwargs={}):
		Thread.__init__(self)
		self.interval = interval
		self.function = function
		self.args = args
		self.kwargs = kwargs
		self.finished = Event()

	def cancel(self):
		"""Stop the timer if it hasn't finished yet"""
		self.finished.set()

	def run(self):
		self.finished.wait(self.interval)
		if not self.finished.is_set():
			self.function(*self.args, **self.kwargs)
		self.finished.set()


class LoopTimer(_Timer):
	"""Call a function after a specified number of seconds:


			t = LoopTimer(30.0, f, args=[], kwargs={})
			t.start()
			t.cancel()     # stop the timer's action if it's still waiting


	"""

	def __init__(self, interval, function, args=[], kwargs={}):
		_Timer.__init__(self, interval, function, args, kwargs)

	def run(self):
		'''self.finished.wait(self.interval)
		if not self.finished.is_set():
			self.function(*self.args, **self.kwargs)
		self.finished.set()'''

		while True:
			self.function(*self.args, **self.kwargs)
			self.finished.wait(self.interval)
			if self.finished.is_set():
				self.finished.set()
				break
			# self.function(*self.args, **self.kwargs)


def _aaa(aaa, bbb, ccc):
	print('aaa')


if __name__ == '__main__':
	t = LoopTimer(1, _aaa, args=[1, 2, 3])
	t.start()
	t.cancel()
	print(get_timestamp())

	for i in day_iterator_by_month(2018, 6):
		print(i)